package com.tianji.promotion.utils;

import lombok.RequiredArgsConstructor;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.EnumMap;
import java.util.Map;
import java.util.function.Function;

@Component
public class LockFactory {
    private final  Map<LockType, Function<String, RLock>> lockTypeHandler;

    public LockFactory(RedissonClient redissonClient) {
        this.lockTypeHandler = new EnumMap<>(LockType.class);
        this.lockTypeHandler.put(LockType.RE_ENTRANT_LOCK, redissonClient::getLock);
        this.lockTypeHandler.put(LockType.FAIR_LOCK, redissonClient::getFairLock);
        this.lockTypeHandler.put(LockType.READ_LOCK, name -> redissonClient.getReadWriteLock(name).readLock());
        this.lockTypeHandler.put(LockType.WRITE_LOCK, name -> redissonClient.getReadWriteLock(name).writeLock());
    }

    public RLock getLock(String name, LockType type) {
        return lockTypeHandler.get(type).apply(name);
    }

}
